package site.tuluan.sp4j.module.sys.service.impl;

import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import site.tuluan.sp4j.common.core.component.token.TokenService;
import site.tuluan.sp4j.common.core.domain.LoginUser;
import site.tuluan.sp4j.common.core.domain.entity.SysUserEntity;
import site.tuluan.sp4j.common.exception.BizException;
import site.tuluan.sp4j.common.utils.security.SecurityUtils;
import site.tuluan.sp4j.module.sys.service.ISysLoginService;
import site.tuluan.sp4j.module.sys.service.ISysUserService;

import javax.annotation.Resource;
import java.util.Map;

@Service
public class SysUserLoginServiceImpl implements ISysLoginService {
    @Resource
    private TokenService tokenService;

    @Resource
    private ISysUserService userService;

    public String login(String userName, String password) throws BizException {
        SysUserEntity sysUser = userService.getUser(userName);

        if (sysUser == null || !sysUser.getPassword().equals(
                userService.calcEncryptedPassword(password, sysUser.getSalt()))) {
            throw new BizException("用户/密码不正确");
        }

        // 为用户生成jwt token，设置过期时长为30分钟
        Map<String, String> payloadMap = Maps.newHashMap();
        return tokenService.geneToken(payloadMap, new LoginUser(sysUser),sysUser.getPassword(), 30 * 60);
    }

    public boolean logout() {
        LoginUser loginUser = SecurityUtils.getCurrentLoginUser();

        if (loginUser == null) {
            return true;
        }

        SecurityUtils.getSubject().logout();

        return tokenService.cleanLoginUser(loginUser.getToken());
    }
}
